package com.goblin.model.socket;

import com.alibaba.fastjson.JSONObject;
import com.goblin.model.media.po.Message;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.websocket.EncodeException;
import javax.websocket.Encoder;
import javax.websocket.EndpointConfig;

public class Encode implements Encoder.Text<Message> {
    private static Logger logger = LoggerFactory.getLogger(SocketServer.class);

    @Override
    public void init(EndpointConfig config) {

    }

    @Override
    public void destroy() {

    }

    //如果你传递的是一个类，则使用如下写法
    @Override
    public String encode(Message msg) throws EncodeException {
        JSONObject jsonObject = new JSONObject();
        JSONObject type = new JSONObject();
        jsonObject.put("content", msg.getContent());
        jsonObject.put("receive", msg.getReceive());
        jsonObject.put("date", msg.getDate());
        jsonObject.put("type", msg.getType());
        JSONObject userFrom = new JSONObject();
        userFrom.put("id", msg.getUserFrom().getId());
        jsonObject.put("userFrom", userFrom);

        logger.debug(jsonObject.toJSONString());

        return jsonObject.toJSONString();
    }
}
